// Http
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, IaxiosResponse, AxiosError } from 'axios'
import { message } from 'antd'

import { API_URL } from '@/config'
import storage from '@/lib/storage'
import { setLogin } from '@/redux/modules/user';
import store from '@/redux';

const service: AxiosInstance = axios.create({
    baseURL: API_URL,
    timeout: 20000
})


service.interceptors.request.use(function (config: AxiosRequestConfig): AxiosRequestConfig {
    // const url = config.url;
    const token = storage.getItem('Authorization');
    if (token && config.headers) {
        config.headers['Authorization'] = token;
        store.dispatch(setLogin({ isLogin: true }))
    }
    return config;
})

service.interceptors.response.use(function (response: AxiosResponse): AxiosResponse {
    return response.data;
}, (err: AxiosError<IaxiosResponse>) => {
    if (err.response) {
        const data = err.response?.data;
        if (data.error_code === 40100) {
            storage.removeItem('Authorization');
            message.info('登录状态过期,请重新登录');
            store.dispatch(setLogin({ isLogin: false }))
        }
    } else if (err.code === 'ECONNABORTED') {
        message.info('请求超时');
        return Promise.reject({
            code: 'timeout',
            message: '请求超时'
        })
    } else {
        message.info(`请求失败:${err.message}`);
    }
    return Promise.reject(err)
})

export default service

declare module 'axios' {
    export interface IaxiosResponse<T = any> {
        error_code: number,
        data: T,
        message: string,
        success?: boolean,
    }
    type GetUpLevel<T> = 0 extends (1 & T) ? IaxiosResponse : T extends Blob ? Blob : IaxiosResponse<T>;
    export interface AxiosInstance {
        <T = any>(config: AxiosRequestConfig): Promise<GetUpLevel<T>>
    }
}